﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Net;
using System.Web;
using HtmlAgilityPack;

namespace ChordAnalizer
{
    public class ChordAnalizerComponent
    {
        private HtmlWeb htmlweb = new HtmlWeb();
        private HtmlDocument htmldoc = new HtmlDocument();
        private object responseStream;

        public static string patternChord = @"^[A-G](b|#)?((m(aj)?|M|aug|dim|sus)([2-7]|9|13)?)?(\/[A-G](b|#)?)?$";

        //public List<string> listChord = new List<string>();

        //Tuple<string, bool> chordLyric = new Tuple<string, bool>("woe", true);

        public static List<Tuple<string, bool>> listStringHasil = new List<Tuple<string, bool>>();
        private static bool okAdd = false;

        private List<string> removeDuplicate(List<string> check)
        {
            List<string> result = new List<string>();
            foreach (string cek in check)
            {
                if (result.Contains(cek) == false)
                {
                    result.Add(cek);
                }
            }
            return result;
        }

        private static void traverse(HtmlNode cur)
        {
            if (cur == null) return;

            if (cur.ParentNode.OriginalName == "span")
            {
                okAdd = true;
            }

            if (cur.OriginalName == "#text")
            {
                if (okAdd)
                {
                    if (cur.ParentNode.OriginalName == "span")
                        listStringHasil.Add(new Tuple<string, bool>(cur.InnerText, true));
                    else
                        listStringHasil.Add(new Tuple<string, bool>(cur.InnerText, false));
                }
            }

            traverse(cur.FirstChild);
            traverse(cur.NextSibling);
        }

        private static bool CheckForInternetConnection()
        {
            try
            {
                using (var client = new WebClient())
                using (var stream = client.OpenRead("http://www.ultimate-guitar.com/"))
                {
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }
        

        /* --------- Searching lagu berdasarkan kategori penyanyi BEGIN --------- */

        public List<string> getURLbyArtist(string keywords)
        {
            List<string> hasil = new List<string>();
            for (int i = 1; i < 6; i++)
            {
                HtmlDocument document = new HtmlDocument();
                HtmlWeb web = new HtmlWeb();
                string stringLengkap = null;
                string searchKey = null;
                string checkedKey = null;
                searchKey = keywords.Replace(" ", "+");
                checkedKey = keywords.Replace(" ", "_");

                try
                {
                    string url = "http://www.ultimate-guitar.com/search.php?title=" + keywords + "&page=" + i + "&tab_type_group=text&app_name=ugt&order=myweight";
                    htmldoc = htmlweb.Load(url);
                    HtmlNodeCollection nodes = htmldoc.DocumentNode.SelectNodes("//a[@class='song']");
                    if (nodes == null)
                        break;

                    foreach (HtmlNode node in nodes)
                    {
                        if (node.Attributes["href"].Value.Contains("crd"))
                        {
                            string[] cekArtis = node.Attributes["href"].Value.Split('/');
                            if (cekArtis[4].Contains(checkedKey))
                            {
                                cekArtis[5] = cekArtis[5].Substring(0, (cekArtis[5].Length) - 8);
                                stringLengkap = cekArtis[4];
                                stringLengkap = string.Concat(stringLengkap, "~", cekArtis[5]);
                                stringLengkap = string.Concat(stringLengkap, "~", node.Attributes["href"].Value);
                                hasil.Add(stringLengkap);
                            }
                        }
                    }
                }
                catch (WebException e)
                {
                    hasil.Add(e.Message);
                }
            }
            return removeDuplicate(hasil);
        }
        /* --------- Searching lagu berdasarkan kategori penyanyi END --------- */



        /* --------- Searching lagu berdasarkan kategori judul BEGIN --------- */

        public List<string> getURLbyTitle(string keywords)
        {
            List<string> hasil = new List<string>();
            for (int i = 1; i < 6; i++)
            {
                HtmlDocument document = new HtmlDocument();
                HtmlWeb web = new HtmlWeb();
                string stringLengkap = null;
                string searchKey = null;
                string checkedKey = null;
                searchKey = keywords.Replace(" ", "+");
                checkedKey = keywords.Replace(" ", "_");

                try
                {
                    string url = "http://www.ultimate-guitar.com/search.php?title=" + keywords + "&page=" + i + "&tab_type_group=text&app_name=ugt&order=myweight";
                    htmldoc = htmlweb.Load(url);
                    HtmlNodeCollection nodes = htmldoc.DocumentNode.SelectNodes("//a[@class='song']");
                    if (nodes == null)
                        break;

                    foreach (HtmlNode node in nodes)
                    {
                        if (node.Attributes["href"].Value.Contains("crd"))
                        {
                            string[] cekJudul = node.Attributes["href"].Value.Split('/');
                            if (cekJudul[5].Contains(checkedKey))
                            {
                                cekJudul[5] = cekJudul[5].Substring(0, (cekJudul[5].Length) - 8);
                                stringLengkap = cekJudul[4];
                                stringLengkap = string.Concat(stringLengkap, "~", cekJudul[5]);
                                stringLengkap = string.Concat(stringLengkap, "~", node.Attributes["href"].Value);
                                hasil.Add(stringLengkap);
                            }
                        }
                    }
                }
                catch (WebException e)
                {
                    hasil.Add(e.Message);
                }
            }
            return removeDuplicate(hasil);
        }
        /* --------- Searching lagu berdasarkan kategori judul END --------- */



        /* --------- Menampilkan lirik dan chord lagu BEGIN --------- */

        public void getLyricAndChord(string keywords)
        {
            string result = null;
            HtmlWeb web = new HtmlWeb();
            HtmlDocument document = new HtmlDocument();

            document = web.Load(keywords);
            int cc = 0;
            HtmlNodeCollection nodes = document.DocumentNode.SelectNodes("//pre");
            okAdd = false;
            listStringHasil = new List<Tuple<string, bool>>();

            foreach (HtmlNode node in nodes)
            {
                ++cc;
                result = node.InnerText;
                if (cc == 2)
                {
                    traverse(node);
                }
            }
        }
        /* --------- Menampilkan lirik dan chord lagu END --------- */



        /* --------- Menampilkan chord yang digunakan dalam suatu lagu BEGIN --------- */

        public string getChordOnly(string cmpChord)
        {
            string hasil = null;
            try
            {
                if (cmpChord == "D" || cmpChord == "A" || cmpChord == "E" || cmpChord == "G" || cmpChord == "C" ||
                    cmpChord == "Amin" || cmpChord == "Dmin" || cmpChord == "Emin" ||
                    cmpChord == "G7" || cmpChord == "C7" || cmpChord == "B7" || cmpChord == "A7" || cmpChord == "D7" || cmpChord == "E7" ||
                    cmpChord == "Asus2" || cmpChord == "Dsus2" || cmpChord == "Esus2" || cmpChord == "Asus4" || cmpChord == "Dsus4" || cmpChord == "Esus4")
                {
                    hasil = "http://justinguitar.com/images/CH_images/Chord-O-" + cmpChord + ".gif";
                }
                else if (cmpChord == "F")
                {
                    hasil = "http://justinguitar.com/images/BCv2_images/161-F-chord-no6.gif";
                }
                else if (cmpChord == "D/F#")
                {
                    hasil = "http://justinguitar.com/images/BCv2_images/191-D_Fsharp-chord.gif";
                }
                else if (cmpChord == "G/B")
                {
                    hasil = "http://justinguitar.com/images/BCv2_images/191-G_B-chord-v1.gif";
                }
                else if (cmpChord == "C/G")
                {
                    hasil = "http://justinguitar.com/images/BCv2_images/191-C_G-chord-v2.gif";
                }
                else if (cmpChord == "G5")
                {
                    hasil = "http://justinguitar.com/images/BCv2_images/172-G5-chord.gif";
                }
                else if (cmpChord == "C5")
                {
                    hasil = "http://justinguitar.com/images/BCv2_images/186-C5-chord.gif";
                }
                else if (cmpChord == "CE7")
                {
                    hasil = "http://justinguitar.com/images/CH_images/Chord-CE-7.gif";
                }
                else if (cmpChord == "CEmaj")
                {
                    hasil = "http://justinguitar.com/images/CH_images/Chord-CE-Maj.gif";
                }
                else if (cmpChord == "CEmaj7")
                {
                    hasil = "http://justinguitar.com/images/CH_images/Chord-CE-Maj7.gif";
                }
                else if (cmpChord == "CEmin")
                {
                    hasil = "http://justinguitar.com/images/CH_images/Chord-CE-min.gif";
                }
                else if (cmpChord == "CEmin7")
                {
                    hasil = "http://justinguitar.com/images/CH_images/Chord-CE-min7.gif";
                }
                else if (cmpChord == "CAmaj")
                {
                    hasil = "http://justinguitar.com/images/CH_images/Chord-CA-Maj.gif";
                }
                else if (cmpChord == "CAmaj7")
                {
                    hasil = "http://justinguitar.com/images/CH_images/Chord-CA-Maj7.gif";
                }
                else if (cmpChord == "CA7")
                {
                    hasil = "http://justinguitar.com/images/CH_images/Chord-CA-7.gif";
                }
                else if (cmpChord == "CEdim7")
                {
                    hasil = "http://justinguitar.com/images/CH_images/Chord-CE-Dim7.gif";
                }
                else if (cmpChord == "CAdim7")
                {
                    hasil = "http://justinguitar.com/images/CH_images/Chord-CA-Dim7.gif";
                }
                return hasil;
            }
            catch (WebException e)
            {
                hasil = e.Message;
            }
            return hasil;
        }
        /* --------- Menampilkan chord yang digunakan dalam suatu lagu END --------- */



        /* --------- Transpose Chord BEGIN --------- */
        public string transpose(string key)
        {
            string transposed = null;
            if (key[0].Equals('C'))
            {
                if (key[1].Equals('#'))
                {
                    transposed = "D" + key.Substring(2, (key.Length - 2));
                }
                else transposed = "C#" + key.Substring(1, (key.Length - 1));
            }
            else if (key[0].Equals('D'))
            {
                if (key[1].Equals('#'))
                {
                    transposed = "E" + key.Substring(2, (key.Length - 2));
                }
                else transposed = "D#" + key.Substring(1, (key.Length - 1));
            }
            else if (key[0].Equals('E'))
            {
                transposed = "F" + key.Substring(1, (key.Length - 1));
            }
            else if (key[0].Equals('F'))
            {
                if (key[1].Equals('#'))
                {
                    transposed = "G" + key.Substring(2, (key.Length - 2));
                }
                else transposed = "F#" + key.Substring(1, (key.Length - 1));
            }
            else if (key[0].Equals('G'))
            {
                if (key[1].Equals('#'))
                {
                    transposed = "A" + key.Substring(2, (key.Length - 2));
                }
                else transposed = "G#" + key.Substring(1, (key.Length - 1));
            }
            else if (key[0].Equals('A'))
            {
                if (key[1].Equals('#'))
                {
                    transposed = "B" + key.Substring(2, (key.Length - 2));
                }
                else transposed = "A#" + key.Substring(1, (key.Length - 1));
            }
            else if (key[0].Equals('B'))
            {
                transposed = "C" + key.Substring(1, (key.Length - 1));
            }
            return transposed;
        }
        /* --------- Transpose Chord END --------- */


    }
}
